
module WindowModifyCustomer where

import Graphics.UI.Gtk
import Customer
import Data.IORef
import MainHandler

windowModifyCustomer iocustomer refHandler combo= do
    customer <- iocustomer
    initGUI
    window <- windowNew
    windowSetPosition window WinPosCenter
    
    labelCustomerTitle <- labelNew (Just "Cliente:")
    labelCustomer <- labelNew (Just (getCustomerName customer))
    labelNewName <- labelNew (Just "Nuevo nombre:")
    
    entryName <- entryNew
    
    buttonAceptar <- buttonNewWithLabel "Aceptar"
    onClicked buttonAceptar (modifyCustomer customer refHandler entryName window combo)
    buttonVolver <- buttonNewWithLabel "Volver"
    onClicked buttonVolver (widgetDestroy window)
    
    vbox <- vBoxNew False 10
    
    set window [windowTitle := "Modificar cliente",windowDefaultWidth := 150,
        windowDefaultHeight := 150, containerBorderWidth := 10, containerChild := vbox]
  

      
    boxPackStart vbox labelCustomerTitle PackNatural 1
    boxPackStart vbox labelCustomer PackNatural 1
    boxPackStart vbox labelNewName PackNatural 1
    boxPackStart vbox entryName PackNatural 1
    boxPackStart vbox buttonAceptar PackNatural 1
    boxPackStart vbox buttonVolver PackNatural 1
    
    
    widgetShowAll window
    
    
    
---------------------------------------------------------------------------
-----------------FUNCIONES DE CONTROL--------------------------------------
---------------------------------------------------------------------------
    
modifyCustomer customer ref entry win combo= do
    newName <- entryGetText entry
    modifyIORef ref (modifyCtmOnDb customer newName)
    addMsg <- (messageDialogNew (Just win) [DialogDestroyWithParent] MessageInfo ButtonsOk "Cliente modificado")
    dialogRun addMsg
    widgetDestroy win 
    updateCombo combo ref
    return ()
    
    
modifyCtmOnDb customer newName handler =
    let newCtmList = changeCtm customer newName (getCustomers handler)
        in setNewCustomerList handler newCtmList
        
changeCtm customer newName (c:cs) = 
    if ((getCustomerName customer) == (getCustomerName c))
        then (setCustomerName c newName): cs
        else c : (changeCtm customer newName cs)
    
 
updateCombo combo db = do
    customers <- readIORef db
    store <- listStoreNew (getCustomers customers)
    comboBoxSetModel combo (Just store)
    customStoreSetColumn store textColumn3 (getCustomerName)
    
textColumn3 :: ColumnId Customer String
textColumn3 = makeColumnIdString 0

